package com.xoa.service.budget;

import com.xoa.dao.budget.BudgetItemMapper;
import com.xoa.dao.budget.BudgetLogMapper;
import com.xoa.dao.budget.BudgetingProcessMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunAttachMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.budget.BudgetItem;
import com.xoa.model.budget.BudgetLog;
import com.xoa.model.budget.BudgetingProcessFlowRunPrcs;
import com.xoa.model.common.SysPara;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunAttach;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.*;
import com.xoa.util.budgetUtil.DateSubString;
import com.xoa.util.budgetUtil.budgeUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BudgetItemManageService {

    @Autowired
    BudgetItemMapper budgetItemMapper;
    @Autowired
    BudgetLogMapper budgetLogMapper;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    FlowRunAttachMapper flowRunAttachMapper;
    @Autowired
    FlowRunMapper flowRunMapper;
    @Autowired
    FlowRunPrcsMapper flowRunPrcsMapper;

    @Autowired
    private BudgetingProcessMapper budgetingProcessMapper;

    @Autowired
    private EnclosureService enclosureService;

    @Resource
    private SysParaMapper sysParaMapper;

    @Resource
    private UserPrivMapper userPrivMapper;

    private static BudgetItemManageService b;

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：新建预算项目
     * 参数说明：
     */
    @Transactional
    public ToJson<BudgetItem> addBudgetItem(HttpServletRequest request, BudgetItem budgetItem) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {

            BudgetItem budgetItem1 = budgetItemMapper.selByName(budgetItem.getBudgetItemName());

            if (budgetItem1 != null) {
                json.setMsg("新建项目重复");
                return json;
            }


            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);


            String userName = user.getUserName();
            String userPhone = usersMapper.selUserPhoneByName(userName);

            budgetItem.setUserId(userName);
            if (userPhone != null && !StringUtils.checkNull(userPhone)) {
                budgetItem.setUserId(userPhone);
            }

            budgetItem.setYear(String.valueOf(budgetItem.getBudgetItemBegindate().getYear() + 1900));

            if (budgetItem.getPriveItem().equals("请选择上级项目(不选为一级项目)") || budgetItem.getPriveItem() == null) {
                budgetItem.setPriveItem("无");
            }

            budgetItem.setRemainingAmount(budgetItem.getItemMoney());
            String pId = budgetItem.getPriveItem();
            if (pId == null || pId.equals("")) {
                budgetItem.setPriveItem(" ");
            }

            int count = budgetItemMapper.insertSelective(budgetItem);

            if (count > 0) {

                BudgetLog budgetLog = new BudgetLog();

                //获取当前时间
                Date dateTime = new Date();
                String time = DateFormat.getStrDate(dateTime);
                InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
                String hostAddress = address.getHostAddress();
                budgetLog.setType("新建");
                budgetLog.setBudgetInputTime(budgetItem.getInputTime());
                budgetLog.setBudgetItemName(budgetItem.getBudgetItemName());
                budgetLog.setIp(hostAddress);
                budgetLog.setUserId(user.getUserName());
                budgetLog.setRemark("无");
                budgetLog.setTime(time.toString());
                //budgetLog.setBudgetId(condition.getBudgetId());
                budgetLogMapper.insertSelective(budgetLog);

                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id删除预算项目
     * 参数说明：
     */
    @Transactional
    public ToJson<BudgetItem> delBudgetItemById(HttpServletRequest request, BudgetItem budgetItem, int type) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        int count = 0;
        try {
            if (type == 1) {
                count = budgetItemMapper.deleteByPrimaryKey(budgetItem.getBudgetId());
            } else if (type == 0) {//假删除
                count = budgetItemMapper.updateDelByPrimaryKey(budgetItem.getBudgetId());
            } else if (type == 2) {
                count = budgetItemMapper.updatefhByPrimaryKey(budgetItem.getBudgetId());
            }
            if (count > 0) {
               /* BudgetLog budgetLog=new BudgetLog();
                Users user=SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());

                //获取当前时间
                Date dateTime=new Date();
                String time=DateFormat.getStrDate(dateTime);
                InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
                String hostAddress = address.getHostAddress();
                budgetLog.setType("删除");
                budgetLog.setBudgetInputTime(condition.getInputTime());
                budgetLog.setBudgetItemName(condition.getBudgetItemName());
                budgetLog.setIp(hostAddress);
                budgetLog.setUserId(user.getUserName());
                budgetLog.setRemark("无");
                budgetLog.setTime(time.toString());
                budgetLog.setBudgetId(condition.getBudgetId());
                budgetLogMapper.insertSelective(budgetLog);*/


                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    @Transactional
    public ToJson<BudgetItem> delAttachById1(Integer budgetId) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        int count = 0;
        try {
            count = budgetItemMapper.delAttachById1(budgetId);

            if (count > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;

    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id查询预算项目
     * 参数说明：
     */
    @Transactional
    public ToJson<BudgetItem> selBudgetItemById(Integer budgetId, String company) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {
            NumberFormat nf = NumberFormat.getPercentInstance();
            BudgetItem b = budgetItemMapper.selBudgetItemById1(budgetId);
            if (b != null) {
                //百分比转换
                if (b.getActualExpenditure() == null) {
                    b.setActualExpenditure(BigDecimal.ZERO);
                }
                if (!StringUtils.checkNull(b.getItemMoney() + "") && !StringUtils.checkNull(b.getActualExpenditure() + "")) {
                    BigDecimal itemMoney = b.getItemMoney();
                    BigDecimal actualExpenditure = b.getActualExpenditure();
                    BigDecimal baiFenBi1 = actualExpenditure.divide(itemMoney, 2, BigDecimal.ROUND_HALF_EVEN);
                    String baiFenBi = nf.format(baiFenBi1);
                    b.setBaiFenBi(baiFenBi);
                }

                if (!StringUtils.checkNull(b.getAttachmentId()) && !StringUtils.checkNull(b.getAttachmentName())) {
                    List<Attachment> budget = GetAttachmentListUtil.returnAttachment(b.getAttachmentName(), b.getAttachmentId(), company, "budget");
                    b.setAttachments(budget);
                }

                if (b.getItemExecuter() != null && b.getItemExecuter() != "") {
                    String[] split = b.getItemExecuter().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName()).append(",");
                    }
                    b.setItemExecuterName(stringBuilder.toString());
                }

                if (b.getItemManager() != null && b.getItemManager() != "") {
                    String[] split = b.getItemManager().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName()).append(",");
                    }
                    b.setItemManagerName(stringBuilder.toString());
                }

                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                b.setAllAdvance(allAdvance);
                b.setRealRemainingAmount(b.getRemainingAmount());
                b.setRemainingAmount((b.getRealRemainingAmount()).subtract(allAdvance));


                json.setMsg("ok");
                json.setObject(b);
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id修改预算项目
     * 参数说明：
     */

    @Transactional
    public ToJson<BudgetItem> upBudgetItemById(HttpServletRequest request, BudgetItem budgetItem) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {
            BudgetItem budgetItem1 = budgetItemMapper.selBudgetItemById(budgetItem.getBudgetId());
            BigDecimal additional = BigDecimal.ZERO;
            if (budgetItem.getItemMoney() != null) {
                additional = budgetItem.getItemMoney();
                budgetItem.setRemainingAmount(budgetItem1.getRemainingAmount().add(budgetItem.getItemMoney()));
                budgetItem.setItemMoney(budgetItem1.getItemMoney().add(budgetItem.getItemMoney()));
            }
            if (!budgetItem1.getItemMoney().equals(budgetItem.getItemMoney())) {
                if (budgetItem1.getItemMoney().equals(budgetItem1.getRemainingAmount())) {
                    budgetItem.setRemainingAmount(budgetItem.getRemainingAmount());
                }
            }
            int count = budgetItemMapper.updateByPrimaryKeySelective(budgetItem);
            //修改日志留痕功能，暂时这样写，后期优化
            StringBuffer sb = new StringBuffer();

            if (budgetItem.getBudgetItemNo() != null && !budgetItem.getBudgetItemNo().equals(budgetItem1.getBudgetItemNo())) {
                sb.append("项目编号:" + budgetItem1.getBudgetItemNo() + "→" + budgetItem.getBudgetItemNo() + ",");
            }
            if (budgetItem.getBudgetItemName() != null && !budgetItem.getBudgetItemName().equals(budgetItem1.getBudgetItemName())) {
                sb.append("项目名称:" + budgetItem1.getBudgetItemName() + "→" + budgetItem.getBudgetItemName() + ",");
            }
            if (budgetItem.getDeptId() != null && !budgetItem.getDeptId().equals(budgetItem1.getDeptId())) {
                String deptName = departmentMapper.departmentOneSelect(Integer.valueOf(budgetItem.getDeptId()));
                sb.append("所属部门:" + budgetItem1.getDeptName() + "→" + deptName + ",");
            }
            if (budgetItem.getBudgetItemBegindate() != null && !budgetItem.getBudgetItemBegindate().equals(budgetItem1.getBudgetItemBegindate())) {
                sb.append("项目开始时间:" + DateFormat.getDatestr(budgetItem1.getBudgetItemBegindate()) + "→" + DateFormat.getDatestr(budgetItem.getBudgetItemBegindate()) + ",");
            }
            if (budgetItem.getBudgetItemEnddate() != null && !budgetItem.getBudgetItemEnddate().equals(budgetItem1.getBudgetItemEnddate())) {
                sb.append("项目结束时间:" + DateFormat.getDatestr(budgetItem1.getBudgetItemEnddate()) + "→" + DateFormat.getDatestr(budgetItem.getBudgetItemEnddate()) + ",");
            }
            if (budgetItem.getInputTime() != null && !budgetItem.getInputTime().equals(budgetItem1.getInputTime())) {
                sb.append("录入时间:" + DateFormat.getStrDate(budgetItem1.getInputTime()) + "→" + DateFormat.getStrDate(budgetItem.getInputTime()) + ",");
            }
            if (budgetItem.getItemExecuter() != null && !budgetItem.getItemExecuter().equals(budgetItem1.getItemExecuter())) {
                String[] oldNames = budgetItem1.getItemExecuter().split(",");
                String[] newNames = budgetItem.getItemExecuter().split(",");
                Map<String, StringBuilder> map = appendNames(oldNames, newNames);
                sb.append("项目执行人:").append(map.get("oldName")).append("→").append(map.get("newName"));
            }
            if (budgetItem.getItemManager() != null && !budgetItem.getItemManager().equals(budgetItem1.getItemManager())) {
                String[] oldNames = budgetItem1.getItemManager().split(",");
                String[] newNames = budgetItem.getItemManager().split(",");
                Map<String, StringBuilder> map = appendNames(oldNames, newNames);
                sb.append("项目负责人:").append(map.get("oldName")).append("→").append(map.get("newName"));
            }
            if (budgetItem.getLineNo() != null && !budgetItem.getLineNo().equals(budgetItem1.getLineNo())) {
                sb.append("额度号:" + budgetItem1.getLineNo() + "→" + budgetItem.getLineNo() + ",");
            }
            if (budgetItem.getQuotaClassify() != null && !budgetItem.getQuotaClassify().equals(budgetItem1.getQuotaClassify())) {
                sb.append("指标分类:" + budgetItem1.getQuotaClassify() + "→" + budgetItem.getQuotaClassify() + ",");
            }
            if (budgetItem.getItemMoney() != null && !budgetItem.getItemMoney().equals(budgetItem1.getItemMoney())) {
                sb.append("项目金额:原有" + budgetItem1.getItemMoney() + "  追加" + additional + ",");
                //sb.append("项目金额:"+budgetItem1.getItemMoney()+"→"+condition.getItemMoney()+",");
            }
            if (budgetItem.getItemDesc() != null && !budgetItem.getItemDesc().equals(budgetItem1.getItemDesc())) {
                sb.append("项目描述:" + budgetItem1.getItemDesc() + "→" + budgetItem.getItemDesc() + ",");
            }
            if (budgetItem.getRemainingAmount() != null && !budgetItem.getRemainingAmount().equals(budgetItem1.getRemainingAmount())) {
                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(budgetItem.getBudgetId());
                sb.append("可用金额:" + budgetItem1.getRemainingAmount().subtract(allAdvance) + "→" + budgetItem.getRemainingAmount().subtract(allAdvance) + ",");
            }
            if (budgetItem.getPriveItem() != null && !budgetItem.getPriveItem().equals(budgetItem1.getPriveItem())) {
                sb.append("上级部门:" + budgetItem1.getPriveItem() + "→" + budgetItem.getPriveItem() + ",");
            }

            if (count > 0) {
                BudgetLog budgetLog = new BudgetLog();
                Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
                String remark = sb.toString();
                //获取当前时间
                Date dateTime = new Date();
                String time = DateFormat.getStrDate(dateTime);
                InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
                String hostAddress = address.getHostAddress();
                budgetLog.setType("修改");
                budgetLog.setBudgetInputTime(budgetItem.getInputTime());
                budgetLog.setBudgetItemName(budgetItem.getBudgetItemName());
                budgetLog.setIp(hostAddress);
                budgetLog.setUserId(user.getUserName());
                budgetLog.setRemark(remark);
                budgetLog.setTime(time.toString());
                budgetLog.setBudgetId(budgetItem.getBudgetId());
                budgetLogMapper.insertSelective(budgetLog);

                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    /**
     * 拼接项目负责人和项目执行人的名字
     *
     * @param oldNames 旧名字数组
     * @param newNames 新名字数组
     * @return map
     */
    private Map<String, StringBuilder> appendNames(String[] oldNames, String[] newNames) {
        StringBuilder oldName = new StringBuilder();
        StringBuilder newName = new StringBuilder();
        for (int i = 0; i < oldNames.length; i++) {
            oldName.append(usersMapper.getUsernameByUserId(oldNames[i])).append(",");
        }
        for (int j = 0; j < newNames.length; j++) {
            newName.append(usersMapper.getUsernameByUserId(newNames[j])).append(",");
        }
        Map<String, StringBuilder> map = new HashMap<>();
        map.put("oldName", oldName);
        map.put("newName", newName);
        return map;
    }

/*
//  反射遍历属性返回不为空的属性名
    private String bianLi(Object obj){

        StringBuffer sb=new StringBuffer();

        Field[] fields = obj.getClass().getDeclaredFields();
        for(int i = 1 , len = fields.length; i < len; i++) {
            // 对于每个属性，获取属性名
            String varName = fields[i].getName();
            try {
                // 获取原来的访问控制权限
                boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                fields[i].setAccessible(true);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o;
                try {
                    o = fields[i].get(obj);
                   if(o!=null&&!o.equals("")){
                       if(varName.equals("budgetItemName")){
                           sb.append("预算项目名称，");
                       }
                       if(varName.equals("budgetItemNo")){
                           sb.append("项目预算号，");
                       }
                       if(varName.equals("department")){
                           sb.append("部门，");
                       }
                       if(varName.equals("inputTime")){
                           sb.append("输入时间，");
                       }
                       if(varName.equals("itemDesc")){
                           sb.append("项目描述，");
                       }
                       if(varName.equals("itemExecuter")){
                           sb.append("项目执行人，");
                       }
                       if(varName.equals("itemMoney")){
                           sb.append("项目金额，");
                       }
                       if(varName.equals("lineNo")){
                           sb.append("额度号，");
                       }
                       if(varName.equals("priveItem")){
                           sb.append("上级项目，");
                       }
                       if(varName.equals("quotaClassify")){
                           sb.append("指标分类，");
                       }
                   }
                } catch (IllegalAccessException e) {

                    e.printStackTrace();
                }
                // 恢复访问控制权限
                fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            }
        }
        return  sb.toString();
    }
*/


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：查询全部预算项目
     * 参数说明：
     */
    public ToJson<BudgetItem> selAllBudget(boolean delFlag, BudgetItem budgetItem, HttpServletRequest request, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("year", budgetItem.getYear());
            if (!StringUtils.checkNull(budgetItem.getDeptId())) {
                // 补充下级部门id
                List<Integer> allDeptIds = addChildDeptIds(budgetItem.getDeptId());
                map.put("deptId", allDeptIds);
            }
            if (budgetItem.getItemExecuter() != null) {
                map.put("itemExecuter", budgetItem.getItemExecuter());
            }
            List<BudgetItem> budgetItems = new ArrayList<BudgetItem>();
            if (delFlag) {//点击已删除
                budgetItems = budgetItemMapper.selDelAllBudget(map);
            } else {
                budgetItems = budgetItemMapper.selAllBudget(map);
            }

            String userPrivName = user.getUserPrivName();

            if (userPrivName.equals("OA管理员")) {
                for (BudgetItem b : budgetItems) {
                    b.setIsOpen("0");

                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilder1 = new StringBuilder();

                    if (!StringUtils.checkNull(b.getItemManager())) {
                        List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                        for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                            Users users = usersByUserIdsOrder.get(i);
                            stringBuilder.append(users.getUserName()).append(",");
                        }
                    }
                    if (!StringUtils.checkNull(b.getItemExecuter())) {
                        List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                        for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                            Users users = usersByUserIdsOrder1.get(i);
                            stringBuilder1.append(users.getUserName()).append(",");
                        }
                    }
                    b.setItemManager(stringBuilder.toString());
                    b.setItemExecuter(stringBuilder1.toString());

                    BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                    b.setAllAdvance(allAdvance);
                    b.setRealRemainingAmount(b.getRemainingAmount());
                    b.setRemainingAmount(b.getRealRemainingAmount().subtract(allAdvance));
                }
            } else {
                boolean hasAuth = hasAuth(user.getUserId(), user.getUserPriv());
                for (BudgetItem b : budgetItems) {
                    // 给会计和财务主管编辑和删除的权限
                    if (hasAuth) {
                        b.setIsOpen("0");
                    } else {
                        b.setIsOpen("1");
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilder1 = new StringBuilder();

                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder.get(i);
                        stringBuilder.append(users.getUserName() + ",");
                    }
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder1.get(i);
                        stringBuilder1.append(users.getUserName() + ",");
                    }
                    b.setItemManager(stringBuilder.toString());
                    b.setItemExecuter(stringBuilder1.toString());

                    BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                    b.setAllAdvance(allAdvance);
                    b.setRealRemainingAmount(b.getRemainingAmount());
                    b.setRemainingAmount(b.getRealRemainingAmount().subtract(allAdvance));
                }

            }

            if (budgetItems.size() > 0) {
                json.setObj(budgetItems);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<BudgetItem> selectBudgets(boolean delFlag, BudgetItem budgetItem, HttpServletRequest request,
                                            Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

            Map<String, Object> map = new HashMap<>();
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("year", budgetItem.getYear());
            map.put("itemExecuter", budgetItem.getItemExecuter());
            // 补充下级部门id
            List<Integer> allDeptIds = addChildDeptIds(budgetItem.getDeptId());
            map.put("deptId", allDeptIds);

            // 查询结果集
            List<BudgetItem> budgetItems;
            if (delFlag) {//点击已删除
                budgetItems = budgetItemMapper.selDelAllBudget(map);
            } else {
                budgetItems = budgetItemMapper.selAllBudget(map);
            }

            // 得到结果集中所有管理者和执行者的userId
            StringBuilder allUserIds = new StringBuilder();
            for (BudgetItem b : budgetItems) {
                allUserIds.append(b.getItemManager()).append(b.getItemExecuter());
            }
            // 得到缓存map
            Map<String, String> cacheMap = getCacheMap(allUserIds);

            // 判断是否拥有编辑权限
            boolean hasAuth = hasAuth(user.getUserId(), user.getUserPriv());
            String isOpen = hasAuth ? "0" : "1";

            for (BudgetItem item : budgetItems) {
                item.setIsOpen(isOpen);

                String manager = item.getItemManager();
                String itemManager = getUsernames(cacheMap, manager);
                item.setItemManager(itemManager);

                String executor = item.getItemExecuter();
                String itemExecutor = getUsernames(cacheMap, executor);
                item.setItemExecuter(itemExecutor);

                // todo
                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(item.getBudgetId());
                item.setAllAdvance(allAdvance);
                item.setRealRemainingAmount(item.getRemainingAmount());
                item.setRemainingAmount(item.getRealRemainingAmount().subtract(allAdvance));
            }

            if (budgetItems.size() > 0) {
                json.setObj(budgetItems);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-11
     * 方法介绍：预算导入接口
     * 参数说明：
     */

    @Transactional
    public ToJson<BudgetItem> importBudgetItem(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {

            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
            } else {
                path = path.append(rb.getString("upload.linux"));
            }

            if (file.isEmpty()) {
                json.setMsg("请上传文件");
                return json;
            } else {

                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    InputStream in = file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    BudgetItem budgetItem = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    for (int i = 1; i <= lastRowNum; i++) {
                        budgetItem = new BudgetItem();
                        row = sheetObj.getRow(i);
                        if (row != null) {
                            for (int j = 0; j <= colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //项目排序号
                                            cell.setCellType(CellType.STRING);
                                            budgetItem.setBudgetItemNo(cell.getStringCellValue());
                                            break;
                                        case 1:
                                            //预算项目名称
                                            List<BudgetItem> budgetItem1 = budgetItemMapper.selAllBudget1();
                                            for (BudgetItem b : budgetItem1) {
                                                if (b.getBudgetItemName().equals(cell.getStringCellValue())) {

                                                    json.setMsg("导入项目重复");
                                                    json.setFlag(1);
                                                    return json;
                                                }
                                            }

                                            budgetItem.setBudgetItemName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //上级项目
                                            budgetItem.setPriveItem(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //项目开始时间
//                                            Date dateCellValue = cell.getDateCellValue();
//                                           // Date beginDate = DateFormat.getDates(cell.getDateCellValue());
//                                            budgetItem.setBudgetItemBegindate(dateCellValue);

                                            Date dateCellValue = cell.getDateCellValue();
                                            budgetItem.setBudgetItemBegindate(dateCellValue);
                                            break;
                                        case 4:
                                            //项目结束时间
                                            /*Date dateCellValue1 = cell.getDateCellValue();
                                            //Date endDate = DateFormat.getDates(cell.getStringCellValue());
                                            budgetItem.setBudgetItemEnddate(dateCellValue1);*/
                                            Date dateCellValue1 = cell.getDateCellValue();
                                            budgetItem.setBudgetItemEnddate(dateCellValue1);
                                            break;
                                        case 5:
                                            //录入时间
                                            /*Date dateCellValue2 = cell.getDateCellValue();
                                            //Date inputTime = DateFormat.getDates(cell.getStringCellValue());
                                            budgetItem.setInputTime(dateCellValue2);*/
                                            Date dateCellValue12 = cell.getDateCellValue();
                                            budgetItem.setInputTime(dateCellValue12);
                                            break;
                                        case 6:
                                            //所属部门
                                            String deptName = cell.getStringCellValue();
                                            List<String> deptIdByDeptName = departmentMapper.getDeptIdByDeptName(deptName);
                                            if (deptIdByDeptName != null && deptIdByDeptName.size() > 0) {
                                                budgetItem.setDeptId(deptIdByDeptName.get(0));
                                            }else{
                                                json.setMsg("未找到所属部门");
                                            }
                                            break;
                                        case 7:
                                            //额度号
                                            // String lineNo=String.valueOf(cell.getNumericCellValue());
                                            cell.setCellType(CellType.STRING);
                                            String lineNo = cell.getStringCellValue();
                                            budgetItem.setLineNo(lineNo);
                                            break;
                                        case 8:
                                            //项目金额
                                            cell.setCellType(CellType.STRING);
                                            budgetItem.setItemMoney(budgeUtil.getTwoDecimal(cell.getStringCellValue()));
                                            break;
                                        case 9:
                                            //剩余（可用）金额
                                            cell.setCellType(CellType.STRING);
                                            budgetItem.setRemainingAmount(budgeUtil.getTwoDecimal(cell.getStringCellValue()));
                                            break;
                                        case 10:
                                            //项目负责人
                                            StringBuilder stringBuilder = new StringBuilder();
                                            List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserNamesOrder(cell.getStringCellValue().split(","));
                                            for (int n = 0, size = usersByUserIdsOrder.size(); n < size; n++) {
                                                Users users = usersByUserIdsOrder.get(n);
                                                stringBuilder.append(users.getUserId() + ",");
                                            }
                                            budgetItem.setItemManager(stringBuilder.toString());
                                            break;
                                        case 11:
                                            //项目执行人
                                            StringBuilder stringBuilder1 = new StringBuilder();
                                            List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserNamesOrder(cell.getStringCellValue().split(","));
                                            for (int m = 0, size = usersByUserIdsOrder1.size(); m < size; m++) {
                                                Users users = usersByUserIdsOrder1.get(m);
                                                stringBuilder1.append(users.getUserId() + ",");
                                            }
                                            budgetItem.setItemExecuter(stringBuilder1.toString());
                                            break;
                                        case 12:
                                            //项目描述
                                            budgetItem.setItemDesc(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //填报人姓名
                                            Users userByUserName = usersMapper.getUserByUserName(cell.getStringCellValue());
                                            if(userByUserName!=null){
                                                budgetItem.setUserId(userByUserName.getUserName());
                                            }
                                            break;
                                        case 14:
                                            //填报人电话
//                                            String writerPhone=String.valueOf(cell.getNumericCellValue());
                                            cell.setCellType(CellType.STRING);
                                            String writerPhone = cell.getStringCellValue();
                                            budgetItem.setUserPhone(writerPhone);
                                            break;
                                        case 15:
                                            //指标分类
                                            budgetItem.setQuotaClassify(cell.getStringCellValue());
                                            break;
                                        default:
                                            json.setMsg("error");
                                            break;
                                    }
                                }
                            }
                            if (budgetItem.getDeptId() != null) {
                                budgetItem.setYear(DateFormat.getDatestr(budgetItem.getBudgetItemBegindate()).substring(0, 4));
                                //condition.setRemainingAmount(condition.getItemMoney());
                                int count = budgetItemMapper.insertSelective(budgetItem);
                                if (count > 0) {
                                    BudgetLog budgetLog = new BudgetLog();
                                    Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                                    Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

                                    //获取当前时间
                                    Date dateTime = new Date();
                                    String time = DateFormat.getStrDate(dateTime);
                                    InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
                                    String hostAddress = address.getHostAddress();
                                    budgetLog.setType("导入");
                                    budgetLog.setBudgetInputTime(budgetItem.getInputTime());
                                    budgetLog.setBudgetItemName(budgetItem.getBudgetItemName());
                                    budgetLog.setIp(hostAddress);
                                    budgetLog.setUserId(user.getUserName());
                                    budgetLog.setRemark("无");
                                    budgetLog.setTime(time.toString());
                                    budgetLog.setBudgetId(budgetItem.getBudgetId());
                                    budgetLogMapper.insertSelective(budgetLog);
                                    json.setMsg("ok");
                                    json.setFlag(0);

                                }
                            }

                        }

                    }

                    dest.delete();

                }

            }


        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-11
     * 方法介绍：预算导出接口
     * 参数说明：
     */

    @Transactional
    public ToJson<BudgetItem> outputBudgetItem(BudgetItem budgetItem, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {

            List<BudgetItem> budgetItems = budgetItemMapper.selAllBudget1();


            for (BudgetItem b : budgetItems) {
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder1 = new StringBuilder();
                b.setInputTime1(DateSubString.StringChange(b.getInputTime()));
                b.setBudgetItemBegindate1(DateSubString.StringChange(b.getBudgetItemBegindate()));
                b.setBudgetItemEnddate1(DateSubString.StringChange(b.getBudgetItemEnddate()));
                if (!StringUtils.checkNull(b.getItemManager())) {
                        List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                        for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                            Users users = usersByUserIdsOrder1.get(i);
                            stringBuilder1.append(users.getUserName()).append(",");
                        }

                }
                if (!StringUtils.checkNull(b.getItemExecuter())) {
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder1.get(i);
                        stringBuilder.append(users.getUserName()).append(",");
                    }

                }
                b.setItemManager(stringBuilder1.toString());//负责人
                b.setItemExecuter(stringBuilder.toString());//执行人
            }

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("预算项目", 22);
            String[] secondTitles = {"项目排序号", "预算项目名称", "项目开始时间", "项目结束时间", "录入时间", "所属部门",
                    "额度号", "上级项目", "项目金额", "项目负责人", "项目执行人", "项目描述",
                    "填报人姓名", "指标分类"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            String[] beanProperty = {"budgetItemNo", "budgetItemName", "budgetItemBegindate1", "budgetItemEnddate1", "inputTime1", "deptName",
                    "lineNo", "priveItem", "itemMoney", "itemManager", "itemExecuter", "itemDesc",
                    "userId", "quotaClassify"};
            HSSFWorkbook workbook = null;
            workbook = ExcelUtil.exportExcelData(workbook2, budgetItems, beanProperty);
            OutputStream out = response.getOutputStream();
            String filename = "预算项目记录表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：查看日志
     * 参数说明：
     */

    @Transactional
    public ToJson<BudgetLog> selBudgetLog(BudgetItem budgetItem, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetLog> json = new ToJson<>(1, "error");

        try {

            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("budgetId", budgetItem.getBudgetId());

            List<BudgetLog> budgetItems = budgetLogMapper.selBudgetLog(map);

            if (budgetItems.size() > 0 && budgetItems != null) {
                json.setObj(budgetItems);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：查询全部日志
     * 参数说明：
     */
    @Transactional
    public ToJson<BudgetLog> selAllBudgetLog(Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetLog> json = new ToJson<>(1, "error");

        try {

            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);


            List<BudgetLog> budgetItems = budgetLogMapper.selAllBudgetLog(map);

            for (BudgetLog b : budgetItems) {
                if (b.getTime() != null) {
                    b.setTime(b.getTime().substring(0, 19));
                }
            }

            if (budgetItems.size() > 0 && budgetItems != null) {
                json.setObj(budgetItems);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：添加日志权限
     * 参数说明：
     */

   /* @Transactional
    public ToJson<BudgetLog> upBudgetLogSet(String userIds,String userPrivIds) {
        ToJson<BudgetLog> json = new ToJson<>(1, "error");

        try {

            Set<String>  userIdLists=new HashSet<>();

            if(userIds!=null && !StringUtils.checkNull(userIds)) {

                String[] userId = userIds.split(",");
                List<String> userIdList = Arrays.asList(userId);
                userIdLists.addAll(userIdList);
            }
            if (userPrivIds != null && !StringUtils.checkNull(userPrivIds)) {
                String[] userPrivId = userPrivIds.split(",");
                List<String> userPrivId1 =new ArrayList<>(Arrays.asList(userPrivId));

                if (userIdList1.size() > 0) {
                    for(Users u:userIdList1){
                        userIdLists.add(u.getUserId());
                    }

                }
            }
            List<String> userIdLists1 =new ArrayList<>(userIdLists);
            if(userIdLists1.size()>0){
                usersMapper.upBudgetLogSet(userIdLists1);
            }

            json.setMsg("ok");
            json.setFlag(0);

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }
*/
    @Transactional
    public ToJson<BudgetLog> delBudgetLogSetById(Integer logId) {
        ToJson<BudgetLog> json = new ToJson<>(1, "error");

        try {

            int count = budgetLogMapper.deleteByPrimaryKey(logId);

            if (count > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }





   /* @Transactional
    public ToJson<Users> selBudgetLogSet() {
        ToJson<Users> json = new ToJson<>(1, "error");

        try {

            List<Users> qx=usersMapper.selBudgetLogSet1();

            if(qx.size()>0) {
                json.setObj(qx);
                json.setMsg("ok");
                json.setFlag(0);

            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }*/


   /* @Transactional
    public ToJson<Users> delBudgetLog() {
        ToJson<Users> json = new ToJson<>(1, "error");

        try {

            int count=usersMapper.delBudgetLog();

            if(count>0) {

                json.setMsg("ok");
                json.setFlag(0);

            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }*/


    @Transactional
    public ToJson<FlowRunAttach> selAllAttach(HttpServletRequest request, String attachmentName, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<FlowRunAttach> json = new ToJson<>(1, "error");
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");

        try {

            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("attachmentName", attachmentName);
            List<FlowRunAttach> flowRunAttach = flowRunAttachMapper.selAllAttach(map);


            List<FlowRunAttach> attachList = new ArrayList<>();

            for (FlowRunAttach f : flowRunAttach) {
                String name = f.getAttachmentName();
                String ID = f.getAttachmentId();
                if (!name.equals("") && !ID.equals("")) {
                    List<Attachment> list = GetAttachmentListUtil.returnAttachment(f.getAttachmentName(), f.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_WORKFLOW);
                    f.setAttachments(list);
                    FlowRun flowRun = flowRunMapper.selectByRunId(f.getRunId());
                    FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.queryByRunId(f.getRunId());
                    f.setSetUploadTime1(f.getUploadTime());
                    f.setFlowName(flowRun.getRunName());
                    f.setFlowId(flowRun.getFlowId());
                    f.setPrscId(flowRunPrcs.getFlowPrcs());
                    attachList.add(f);
                }

            }


            if (flowRunAttach.size() > 0 && flowRunAttach != null) {
                json.setObj(attachList);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    public List<Attachment> returnAttachment(String attachmentName, String attachmentId, String sqlType, String module) {
        List<Attachment> list = new ArrayList<Attachment>();
        if (StringUtils.checkNull(attachmentId) && StringUtils.checkNull(attachmentName)) {
            return list;
        } else {
            try {
                if (attachmentId.contains("@")) {
                    String[] attachmentIds = attachmentId.split(",");
                    String[] attachmentNames = attachmentName.split("\\*");
                    int attachmentidLength = attachmentIds.length;
                    for (int i = 0; i < attachmentidLength; i++) {
                        Attachment attachment = enclosureService.findByAttachId1(Integer.parseInt(attachmentIds[i].substring(0, attachmentIds[i].indexOf("@"))));
                        if (attachment != null) {
                            attachment.setAttUrl("AID=" + attachment.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId() + "&ATTACHMENT_NAME=" + attachment.getAttachName());
                            StringBuffer id = new StringBuffer();
                            StringBuffer name = new StringBuffer();
                            int aid = attachment.getAid();
                            String attachId = attachment.getAttachId();
                            String ym = attachment.getYm();
                            String attachName = attachment.getAttachName();
                            String all = aid + "@" + ym + "_" + attachId;
                            id.append(all).append(",");
                            name.append(attachName).append("*");
                            attachment.setId(id.toString());
                            attachment.setName(name.toString());
                            list.add(attachment);
                        }
                    }
                } else {

                    String[] attachmentIds = attachmentId.split(",");
                    String[] attachmentNames = attachmentName.split("\\*");
                    int attachmentidLength = attachmentIds.length;
                    for (int i = 0; i < attachmentidLength; i++) {
                /*		Attachment att = new Attachment();
                        att.setAttachName(attachmentNames[i]);
						att.setAid(1024);
						att.setYm(attachmentIds[i].substring(0, attachmentIds[i].lastIndexOf("_")));
						att.setAttachId(Integer.valueOf(attachmentIds[i].substring(attachmentIds[i].indexOf("_") + 1, attachmentIds[i].length())));
						att.setAttUrl("AID=" + att.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + att.getYm() + "&ATTACHMENT_ID=" + att.getAttachId() + "&ATTACHMENT_NAME=" + att.getAttachName());
					*/

                        Attachment attachment = enclosureService.findByAttachId1(Integer.parseInt(attachmentIds[i].substring(0, attachmentIds[i].indexOf("@"))));
                        if (attachment != null) {
                            attachment.setAttUrl("AID=" + attachment.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId() + "&ATTACHMENT_NAME=" + attachment.getAttachName());
                            StringBuffer id = new StringBuffer();
                            StringBuffer name = new StringBuffer();
                            int aid = attachment.getAid();
                            String attachId = attachment.getAttachId();
                            String ym = attachment.getYm();
                            String attachName = attachment.getAttachName();
                            String all = aid + "@" + ym + "_" + attachId;
                            id.append(all).append(",");
                            name.append(attachName).append("*");
                            attachment.setId(id.toString());
                            attachment.setName(name.toString());
                            list.add(attachment);
                        }


                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return list;
        }
    }

    @Transactional
    public ToJson<FlowRunAttach> delAttachById(Integer seqId) {
        ToJson<FlowRunAttach> json = new ToJson<>(1, "error");

        try {

            int count = flowRunAttachMapper.deleteByPrimaryKey(seqId);

            if (count > 0) {

                json.setMsg("ok");
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    @Transactional
    public ToJson<BudgetItem> selStatement(HttpServletRequest request, BudgetItem budgetItem, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetItem> json = new ToJson<>();
        try {

            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams.getPage() - 1);
            map.put("pageSize", pageParams.getPageSize());

            map.put("budgetItemBegindate", budgetItem.getBudgetItemBegindate());
            map.put("budgetItemEnddate", budgetItem.getBudgetItemEnddate());
            map.put("year", budgetItem.getYear());
            map.put("deptId", budgetItem.getDeptId());
            map.put("allow", budgetItem.getStatus());


            if (!StringUtils.checkNull(budgetItem.getItemExecuter()))
                map.put("itemExecuter", budgetItem.getItemExecuter().replace(",", ""));

            if (!StringUtils.checkNull(budgetItem.getBudgetItemName()))
                map.put("budgetItemNames", budgetItem.getBudgetItemName().split(","));

            List<BudgetItem> budgetItems = budgetItemMapper.selStatement(map);


            NumberFormat nf = NumberFormat.getPercentInstance();
            if (budgetItems != null && budgetItems.size() > 0) {
                //预算周期拼接
                for (BudgetItem b : budgetItems) {
                    StringBuffer stringBuffer = new StringBuffer();
                    if (b.getBudgetItemBegindate() != null && b.getBudgetItemEnddate() != null) {
                        stringBuffer.append(DateFormat.getDatestr(b.getBudgetItemBegindate()) + " 至 ").append(DateFormat.getDatestr(b.getBudgetItemEnddate()));
                        b.setBudgetZhouQi(stringBuffer.toString());
                    }
                    //可用金额转换
                    if (b.getActualExpenditure() != null) {
                        /*int zhiChu=Integer.valueOf(b.getActualExpenditure());
                        int itemMoney=Integer.valueOf(b.getRemainingAmount());*/
                        BigDecimal keYong = b.getIsPayment();
                        b.setIsPayment(keYong);
                    }
                    //百分比转换
                    if (b.getActualExpenditure() == null) {
                        b.setActualExpenditure(BigDecimal.ZERO);
                        b.setBaiFenBi("暂无");
                    } else if (!StringUtils.checkNull(b.getItemMoney() + "") && !StringUtils.checkNull(b.getActualExpenditure() + "")) {
                        BigDecimal itemMoney = b.getItemMoney();
                        BigDecimal actualExpenditure = b.getActualExpenditure();
                        BigDecimal baiFenBi1 = actualExpenditure.divide(itemMoney, 2, BigDecimal.ROUND_HALF_EVEN);
                        String baiFenBi = nf.format(baiFenBi1);
                        b.setBaiFenBi(baiFenBi);
                    }
                    //审批状态转换
                    if (b.getAllow().equals("0")) {
                        b.setAllow("待审批");
                    } else if (b.getAllow().equals("1")) {
                        b.setAllow("已批准");
                    } else if (b.getAllow().equals("2")) {
                        b.setAllow("未批准");
                    }

                    Users user = usersMapper.findUsersByuserId(b.getApplicant());
                    b.setApplicant(user.getUserName());

                    if (b.getApplicationDate() != null) {
                        String s = b.getApplicationDate();
                        b.setApplicationDate(s.substring(0, 19));
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilder1 = new StringBuilder();

                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder.get(i);
                        stringBuilder.append(users.getUserName() + ",");
                    }
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder1.get(i);
                        stringBuilder1.append(users.getUserName() + ",");
                    }
                    b.setItemManager(stringBuilder.toString());
                    b.setItemExecuter(stringBuilder1.toString());

                }
            }

            map.remove("page");
            List<BudgetItem> budgetItems1 = budgetItemMapper.selStatistics(map);

            int pageCount = budgetItemMapper.selStatementCount(map);
            json.setTotleNum(pageCount);

            Map<String, Object> objMap = new HashMap<String, Object>();
            List<BudgetItem> budgetItems2 = budgetItemMapper.selStatistics(objMap);

            BigDecimal allMoney = BigDecimal.ZERO;
            BigDecimal allPay = BigDecimal.ZERO;
            for (int i = 0, length = budgetItems2.size(); i < length; i++) {
                BudgetItem budgetItem1 = budgetItems2.get(i);
                allMoney = allMoney.add(budgetItem1.getItemMoney());
                allPay = allPay.add(budgetItem1.getActualExpenditure());
            }
            objMap.put("allMoney", allMoney);
            objMap.put("allPayMoney", allPay);
            objMap.put("allBalance", allMoney.subtract(allPay));

            json.setObj1(objMap);

            json.setObject(budgetItems1);
            json.setObj(budgetItems);

            json.setMsg("ok");
            json.setFlag(0);


        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }

        return json;
    }

    /**
     * 预算执行台账列表查询
     *
     * @param request
     * @param condition
     * @param page
     * @param pageSize
     * @param useFlag
     * @return
     */
    @Transactional
    public ToJson<BudgetItem> selStatement1(HttpServletRequest request, BudgetItem condition, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<BudgetItem> json = new ToJson<>();
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("budgetItem", condition);

            // 补充下级部门id
            List<Integer> allDeptIds = addChildDeptIds(condition.getDeptId());
            map.put("deptId", allDeptIds);

            // 处理“申请人”条件
            String applicants = condition.getApplicant();
            if (!StringUtils.checkNull(applicants)) {
                String[] arr = applicants.split(",");
                map.put("applicant", arr);
            }

            List<BudgetItem> budgetItems = budgetItemMapper.getStatement(map);

            json.setTotleNum(pageParams.getTotal());//TODO
            json.setObj(budgetItems);//
            //System.out.println(json);//

            NumberFormat nf = NumberFormat.getPercentInstance();
            if (budgetItems != null && budgetItems.size() > 0) {
                //预算周期拼接
                for (BudgetItem b : budgetItems) {
                    StringBuffer stringBuffer = new StringBuffer();
                    if (b.getBudgetItemBegindate() != null && b.getBudgetItemEnddate() != null) {
                        stringBuffer.append(b.getBudgetItemBegindate() + " 至 ").append(b.getBudgetItemEnddate());
                        b.setBudgetZhouQi(stringBuffer.toString());
                    }
                    //百分比转换
                    if (!StringUtils.checkNull(b.getItemMoney() + "") && !StringUtils.checkNull(b.getActualExpenditure() + "")) {
                        BigDecimal itemMoney = b.getItemMoney();
                        BigDecimal actualExpenditure = b.getActualExpenditure();
                        BigDecimal baiFenBi1 = actualExpenditure.divide(itemMoney, 2, BigDecimal.ROUND_HALF_EVEN);
                        String baiFenBi = nf.format(baiFenBi1);
                        b.setBaiFenBi(baiFenBi);
                    }
                    //审批状态转换
                    if (b.getAllow().equals("0")) {
                        b.setAllow("待审批");
                    } else if (b.getAllow().equals("1")) {
                        b.setAllow("已批准");
                    } else if (b.getAllow().equals("2")) {
                        b.setAllow("未批准");
                    }

                    Users user = usersMapper.findUsersByuserId(b.getApplicant());
                    b.setApplicant(user.getUserName());

                    if (b.getApplicationDate() != null) {
                        String s = b.getApplicationDate();
                        b.setApplicationDate(s.substring(0, 19));
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilder1 = new StringBuilder();

                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder.get(i);
                        stringBuilder.append(users.getUserName() + ",");
                    }
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder1.get(i);
                        stringBuilder1.append(users.getUserName() + ",");
                    }
                    b.setItemManager(stringBuilder.toString());
                    b.setItemExecuter(stringBuilder1.toString());

                }
            }

            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Map<String, Object> objectMap = new HashMap<String, Object>();
            objectMap.put("userId", users.getUserId());
            for (BudgetItem b : budgetItems) {
                objectMap.put("runid", b.getRunId());

                List<BudgetingProcessFlowRunPrcs> budgetingProcessList = budgetingProcessMapper.queryAllBudgetingProcess1(objectMap);
                if (budgetingProcessList != null && budgetingProcessList.size() > 0) {
                    BudgetingProcessFlowRunPrcs bb = budgetingProcessList.get(0);
                    //flowId=170&flowStep=2&runId=754&prcsId=2
                    HashMap<String, String> map1 = new HashMap<>();
                    map1.put("flowId", bb.getFlowId());
                    map1.put("flowStep", bb.getStep() + "");
                    map1.put("prcsId", bb.getRealPrcsId() + "");

                    b.setMap1(map1);
                    //b.setStatus(budgeUtil.switchSetpName(bb.getRealPrcsId(), bb.getStep(), bb.getPrFlag()));
                    b.setStatus(budgeUtil.switchSetpName(bb));
                }

                //b.setStatus(budgeUtil.switchSetpName(Integer.parseInt(b.getMap1().get("prcsId"))));
            }

            // 添加申请人部门
            for (BudgetItem item : budgetItems) {
                String applicant = item.getApplicant();
                Integer deptId = budgetItemMapper.getDeptIdByUsername(applicant);
                String deptName = budgetItemMapper.getDeptNameByDeptId(deptId);
                item.setDeptName(deptName);
            }

            json.setObj(budgetItems);
            json.setTotleNum(pageParams.getTotal());
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 预算执行台账导出
     *
     * @param budgetItem
     * @param request
     * @param response
     * @param session
     * @return
     */
    @Transactional
    public ToJson<BudgetItem> outputStatement(BudgetItem budgetItem, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        try {
            /*  List<BudgetItem> budgetItems = budgetItemMapper.selAllStatement();*/
            PageParams pageParams = new PageParams();
          /*  pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);*/
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("budgetItem", budgetItem);

            List<BudgetItem> budgetItems = budgetItemMapper.selStatement1(map);
            NumberFormat nf = NumberFormat.getPercentInstance();
            BudgetItem item = new BudgetItem();
            item.setBudgetItemName("合计");
            BigDecimal ysCount = BigDecimal.ZERO;//预算总金额
            BigDecimal kyCount = BigDecimal.ZERO;//可用总金额
            BigDecimal zcCount = BigDecimal.ZERO;//支出总金额
            for (BudgetItem b : budgetItems) {

                if (b.getLineNo() != null && b.getLineNo().contains(",")) {
                    b.setLineNo(b.getLineNo().replaceAll(",", ""));
                }

                StringBuffer stringBuffer = new StringBuffer();
                if (b.getBudgetItemBegindate() != null && b.getBudgetItemEnddate() != null) {
                    stringBuffer.append(DateFormat.getDatestr(b.getBudgetItemBegindate()) + " 至 ").append(DateFormat.getDatestr(b.getBudgetItemEnddate()));
                    b.setBudgetZhouQi(stringBuffer.toString());
                }

                if (b.getActualExpenditure() != null) {
                    BigDecimal zhiChu = b.getActualExpenditure();
                    BigDecimal itemMoney = b.getItemMoney();
                    BigDecimal keYong = itemMoney.subtract(zhiChu);
                    b.setIsPayment(keYong);
                }

                if (b.getItemMoney() != null) {
                    ysCount = ysCount.add(b.getItemMoney());//预算总金额合计
                } else {
                    ysCount = ysCount.add(BigDecimal.ZERO);
                }

                if (b.getActualExpenditure() != null) {
                    zcCount = zcCount.add(b.getActualExpenditure());//支出总金额合计
                } else {
                    zcCount = zcCount.add(BigDecimal.ZERO);
                }
                if (b.getIsPayment() != null) {
                    kyCount = ysCount.add(b.getIsPayment());//可用总金额
                } else {
                    kyCount = ysCount.add(BigDecimal.ZERO);
                }

                //百分比转换
                if (!StringUtils.checkNull(b.getItemMoney() + "") && !StringUtils.checkNull(b.getActualExpenditure() + "")) {
                    BigDecimal itemMoney = b.getItemMoney();
                    BigDecimal actualExpenditure = b.getActualExpenditure();
                    BigDecimal baiFenBi1 = actualExpenditure.divide(itemMoney, 2, BigDecimal.ROUND_HALF_EVEN);
                    String baiFenBi = nf.format(baiFenBi1);
                    b.setBaiFenBi(baiFenBi);
                }
                //审批状态转换
                if (b.getAllow().equals("0")) {
                    b.setAllow("待审批");
                } else if (b.getAllow().equals("1")) {
                    b.setAllow("已批准");
                } else if (b.getAllow().equals("2")) {
                    b.setAllow("未批准");
                }

                Users user = usersMapper.findUsersByuserId(b.getApplicant());
                b.setApplicant(user.getUserName());

                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder1 = new StringBuilder();

                List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                    Users users = usersByUserIdsOrder.get(i);
                    stringBuilder.append(users.getUserName() + ",");
                }
                List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                    Users users = usersByUserIdsOrder1.get(i);
                    stringBuilder1.append(users.getUserName() + ",");
                }
                b.setItemManager(stringBuilder.toString());
                b.setItemExecuter(stringBuilder1.toString());

                b.setApplicationDate(DateSubString.getYearMouth(b.getApplicationDate()));

            }
            item.setIsPayment(kyCount);
            item.setActualExpenditure(zcCount);
            item.setItemMoney(ysCount);
            budgetItems.add(item);
            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("预算报表", 23);
            String[] secondTitles = {"预算项目名称", "项目申请时间", "项目申请人", "项目申请部门", "预算总金额", "额度号", "预算周期", "项目执行人", "项目负责人",
                    "支出金额", "可用金额", "支出进度百分比", "审批状态"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            String[] beanProperty = {"budgetItemName", "applicationDate", "applicant", "deptName", "itemMoney", "lineNo", "budgetZhouQi", "itemExecuter", "itemManager",
                    "actualExpenditure", "isPayment", "baiFenBi", "allow"};
            HSSFWorkbook workbook = null;
            workbook = ExcelUtil.exportExcelData(workbook2, budgetItems, beanProperty);
            OutputStream out = response.getOutputStream();
            String filename = "预算报表记录表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    public String selOneLineNo(String budgetItemName) {
        return budgetItemMapper.selOneLineNo(budgetItemName);
    }


    @Transactional
    public ToJson<BudgetItem> upBudgetItemById1(HttpServletRequest request, BudgetItem budgetItem) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        try {
            int count = budgetItemMapper.updateByPrimaryKeySelective1(budgetItem);
            if (count > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    public ToJson<BudgetItem> selStatistics(BudgetItem budgetItem) {
        ToJson<BudgetItem> json = new ToJson<BudgetItem>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            StringBuilder stringBuilder = new StringBuilder();

            map.put("budgetItemBegindate", budgetItem.getBudgetItemBegindate());
            map.put("budgetItemEnddate", budgetItem.getBudgetItemEnddate());
            map.put("year", budgetItem.getYear());
            map.put("deptId", budgetItem.getDeptId());
            map.put("itemExecuter", budgetItem.getItemExecuter());
            //zzq:如果用户有选择预算项目，想筛选个别项目的预算花费情况：有预算项目的id
            Map<String, Object> objMap = new HashMap<String, Object>();
            BigDecimal allMoney = BigDecimal.ZERO;//预算金额
            BigDecimal allPayMoney = BigDecimal.ZERO;//已支出金额
            BigDecimal allAdvance = BigDecimal.ZERO;// 预支出金额

            // 补充下级部门id
            List<Integer> allDeptIds = addChildDeptIds((String) map.get("deptId"));
            map.put("deptId", allDeptIds);

            if (!StringUtils.checkNull(budgetItem.getBudgetIds())) {
                // budgetId为int型，所以需要转换，以便sql中用in语句判断
                String[] budgetIdsString = budgetItem.getBudgetIds().split(",");
                int[] budgetIds = toIntArray(budgetIdsString);
                map.put("budgetIds", budgetIds);                //用项目客户选择的预算项目（所属部门id、开始时间、结束时间、年度）查出预算项目信息

                List<BudgetItem> budgetItems1 = budgetItemMapper.getStatistics(map);

                json.setObject(budgetItems1);
                for (BudgetItem bItems1 : budgetItems1) {
                    allMoney = allMoney.add(bItems1.getItemMoney());
                    allPayMoney = allPayMoney.add(bItems1.getActualExpenditure());
                    allAdvance = allAdvance.add(bItems1.getAllAdvance());
                    objMap.put("allMoney", allMoney);//设置预算金额
                    objMap.put("allPayMoney", allPayMoney);//设置已支出金额
                    objMap.put("allBalance", allMoney.subtract(allPayMoney).subtract(allAdvance));//设置还剩金额(预算金额-已支出金额-预支出金额)
                    objMap.put("allAdvance", allAdvance);// 设置预支出金额
                    //预算报表-概况统计：加个别项目名
                    String budgetItemName = bItems1.getBudgetItemName();
                    stringBuilder.append(budgetItemName + ",");
                    objMap.put("budgetItemName", stringBuilder);
                }
            } else {
                /*int pageCount = budgetItemMapper.selStatementCount(map);
            json.setTotleNum(pageCount);*/

                //List<BudgetItem> budgetItems2 = budgetItemMapper.selStatistics(map);
                List<BudgetItem> budgetItems2 = budgetItemMapper.getStatistics(map);

                for (int i = 0, length = budgetItems2.size(); i < length; i++) {
                    BudgetItem budgetItem1 = budgetItems2.get(i);
                    allMoney = allMoney.add(budgetItem1.getItemMoney());
                    allPayMoney = allPayMoney.add(budgetItem1.getActualExpenditure());
                    allAdvance = allAdvance.add(budgetItem1.getAllAdvance());
                }
                objMap.put("allMoney", allMoney);//预算金额
                objMap.put("allPayMoney", allPayMoney);//已支出金额
                objMap.put("allBalance", allMoney.subtract(allPayMoney).subtract(allAdvance));//还剩金额
                objMap.put("allAdvance", allAdvance);
                json.setObject(budgetItems2);
            }
            json.setObj1(objMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<BudgetItem> selAllBudgetFlow(HttpServletRequest request, Integer runId, Integer prcsId) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            //jzm添加执行人和项目时间周期进行筛选
            //获取当前登陆人和时间
            if (prcsId != null && (prcsId == 4 || prcsId == 8)) {

            } else {
                Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users loginUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
                String dqUserId = loginUser.getUserId();
                map.put("itemExecuter", dqUserId);
            }
            Date date = new Date();
            map.put("newDate", date);
            List<BudgetItem> budgetItems = budgetItemMapper.selAllBudget(map);

            BigDecimal nowAdvance = BigDecimal.ZERO;
            Map<Integer, Object> advanceMap = new HashMap<Integer, Object>();
            if (runId != null) {
                List<BudgetingProcessFlowRunPrcs> budgetingProcessFlowRunPrcs = budgetingProcessMapper.selBudgetProcessByRunId(runId);
                for (int i = 0, size = budgetingProcessFlowRunPrcs.size(); i < size; i++) {
                    BudgetingProcessFlowRunPrcs budgetingProcessFlowRunPrcs1 = budgetingProcessFlowRunPrcs.get(i);
                    nowAdvance = nowAdvance.subtract(budgetingProcessFlowRunPrcs1.getAdvance());
                    advanceMap.put(budgetingProcessFlowRunPrcs1.getBudgetId(), budgetingProcessFlowRunPrcs1.getAdvance());
                }
            }

            for (BudgetItem b : budgetItems) {
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder1 = new StringBuilder();

                if (!StringUtils.checkNull(b.getItemManager())) {
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder.get(i);
                        stringBuilder.append(users.getUserName() + ",");
                    }
                }
                if (!StringUtils.checkNull(b.getItemExecuter())) {
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int i = 0, size = usersByUserIdsOrder1.size(); i < size; i++) {
                        Users users = usersByUserIdsOrder1.get(i);
                        stringBuilder1.append(users.getUserName() + ",");
                    }
                }
                b.setItemManager(stringBuilder.toString());
                b.setItemExecuter(stringBuilder1.toString());

                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                if (advanceMap.get(b.getBudgetId()) != null) {
                    allAdvance = allAdvance.subtract(budgeUtil.getTwoDecimal(advanceMap.get(b.getBudgetId()) + ""));
                }
                b.setAllAdvance(allAdvance);
                b.setRealRemainingAmount(b.getRemainingAmount());
                b.setRemainingAmount(b.getRealRemainingAmount().subtract(allAdvance));
            }

            json.setObj(budgetItems);
            json.setMsg("ok");
            json.setFlag(0);

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }

    public ToJson<BudgetItem> selBudgetItemByIdFlow1(Integer budgetId, Integer runId) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {
            NumberFormat nf = NumberFormat.getPercentInstance();
            BudgetItem b = budgetItemMapper.selBudgetItemById1(budgetId);
            if (b != null) {
                //百分比转换
                if (b.getActualExpenditure() == null) {
                    b.setActualExpenditure(BigDecimal.ZERO);
                }

                if (b.getItemExecuter() != null && b.getItemExecuter() != "") {
                    String[] split = b.getItemExecuter().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName()).append(",");
                    }
                    b.setItemExecuterName(stringBuilder.toString());
                }

                if (b.getItemManager() != null && b.getItemManager() != "") {
                    String[] split = b.getItemManager().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName());
                    }
                    b.setItemManagerName(stringBuilder.toString());
                }

                BigDecimal nowAdvance = BigDecimal.ZERO;
                if (runId != null) {
                    List<BudgetingProcessFlowRunPrcs> budgetingProcessFlowRunPrcs = budgetingProcessMapper.selBudgetProcessByRunId(runId);
                    for (int i = 0, size = budgetingProcessFlowRunPrcs.size(); i < size; i++) {
                        nowAdvance = nowAdvance.add(budgetingProcessFlowRunPrcs.get(i).getAdvance());
                    }
                }

                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                b.setAllAdvance(allAdvance.subtract(nowAdvance));
                b.setRealRemainingAmount(b.getRemainingAmount());
                b.setRemainingAmount(b.getRealRemainingAmount().subtract(b.getAllAdvance()));


                json.setMsg("ok");
                json.setObject(b);
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    public ToJson<BudgetItem> selBudgetItemByIdFlow(Integer budgetId, Integer runId) {
        ToJson<BudgetItem> json = new ToJson<>(1, "error");

        try {
            BudgetItem b = budgetItemMapper.selBudgetItemById1(budgetId);
            if (b != null) {
                if (b.getItemExecuter() != null && b.getItemExecuter() != null) {
                    String[] split = b.getItemExecuter().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName()).append(",");
                    }
                    b.setItemExecuterName(stringBuilder.toString());
                }

                if (b.getItemManager() != null && b.getItemManager() != null) {
                    String[] split = b.getItemManager().split(",");
                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(split);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0, size = usersByUserIdsOrder.size(); i < size; i++) {
                        stringBuilder.append(usersByUserIdsOrder.get(i).getUserName());
                    }
                    b.setItemManagerName(stringBuilder.toString());
                }

                BigDecimal nowAdvance = BigDecimal.ZERO;
                if (runId != null) {
                    List<BudgetingProcessFlowRunPrcs> budgetingProcessFlowRunPrcs = budgetingProcessMapper.selBudgetProcessByRunId(runId);
                    for (int i = 0, size = budgetingProcessFlowRunPrcs.size(); i < size; i++) {
                        nowAdvance = nowAdvance.add(budgetingProcessFlowRunPrcs.get(i).getAdvance());
                    }
                }

//                Integer allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetId(b.getBudgetId());
                Map map = new HashMap();
                map.put("budgetId", budgetId);
                map.put("runId", runId);
                BigDecimal allAdvance = budgetingProcessMapper.selAllAdvanceByBudgetIdAndRunId(map);
                b.setAllAdvance(allAdvance);//预支出金额
                b.setActualExpenditure(b.getItemMoney().subtract(b.getRemainingAmount()));//项目已支出（项目总金额减去剩余金额）
                b.setRealRemainingAmount(b.getRemainingAmount());
                b.setRemainingAmount(b.getRealRemainingAmount().subtract(allAdvance));

                json.setMsg("ok");
                json.setObject(b);
                json.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }

        return json;
    }


    public Integer generateBudgetNo(HttpServletRequest request) {
        //获取当年年份
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        //获取最大排序号
        String subBugetNo = "00";
        String bugetNo = budgetItemMapper.selLastBudgetNo();
        if(!StringUtils.checkNull(bugetNo)){
            subBugetNo = bugetNo.substring(4, bugetNo.getBytes().length);
        }

        return Integer.valueOf(year + subBugetNo) + 1;
    }

    /**
     * 设置编辑权限
     *
     * @param users 用户姓名字符串
     * @param privs 角色名称字符串
     */
    public void setEditAuth(String users, String privs) {
        if (users != null) {
            SysPara permitUser = new SysPara();
            permitUser.setParaName("BUDGET_EDIT_USER");
            permitUser.setParaValue(users);
            sysParaMapper.updateSysPara(permitUser);
        }
        if (privs != null) {
            SysPara permitPriv = new SysPara();
            permitPriv.setParaName("BUDGET_EDIT_PRIV");
            permitPriv.setParaValue(privs);
            sysParaMapper.updateSysPara(permitPriv);
        }
    }

    /**
     * 回显编辑权限
     *
     * @return {用户姓名,角色名称，用户id，角色id}
     */
    public String[] seeEditAuth() {
        SysPara user = sysParaMapper.querySysPara("BUDGET_EDIT_USER");
        SysPara priv = sysParaMapper.querySysPara("BUDGET_EDIT_PRIV");
        String userIds = user.getParaValue();
        String privNos = priv.getParaValue();

        StringBuilder usernames = new StringBuilder();
        if (!StringUtils.checkNull(userIds)) {
            String[] userIdsArray = userIds.split(",");
            for (String userId : userIdsArray) {
                String username = usersMapper.getUsernameByUserId(userId);
                if(!StringUtils.checkNull(username)){
                    usernames.append(username).append(",");
                }

            }
        }
        StringBuilder privNames = new StringBuilder();
        if (!StringUtils.checkNull(privNos)) {
            String[] privNosArray = privNos.split(",");
            for (String privNo : privNosArray) {
                UserPriv userPriv = userPrivMapper.selectByPrimaryKey(Integer.valueOf(privNo));
                if(userPriv!=null){
                    privNames.append(userPriv.getPrivName()).append(",");
                }
            }
        }
        return new String[]{usernames.toString(), privNames.toString(), userIds, privNos};
    }

    /**
     * 字符串型数组转为整型数组
     *
     * @param a 字符串型数组
     * @return 整型数组
     */
    private int[] toIntArray(String[] a) {
        if (a == null) {
            return null;
        }
        int[] result = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            result[i] = Integer.valueOf(a[i]);
        }
        return result;
    }

    /**
     * 添加子部门id
     *
     * @param parent 父部门id
     * @return 父部门id和子部门id的list
     */
    private List<Integer> addChildDeptIds(String parent) {
        if (StringUtils.checkNull(parent)) {
            return null;
        }
        int parentId = Integer.valueOf(parent);
        List<Integer> childs = departmentMapper.getDeptIdByParent(parentId);
        childs.add(parentId);
        return childs;
    }

    /**
     * 判断有没有编辑权限
     *
     * @param userId 当前用户id
     * @param privId 当前用户角色id
     * @return true-有 false-没
     */
    private boolean hasAuth(String userId, Integer privId) {
        // OA管理员拥有编辑权限
        if (privId == 1) {
            return true;
        }

        // 得到权限编号
        UserPriv userPriv = userPrivMapper.selectByPrimaryKey(privId);
        String privNo = String.valueOf(userPriv.getPrivNo());

        // 拥有权限的userId串
        SysPara user = sysParaMapper.querySysPara("BUDGET_EDIT_USER");
        // 拥有权限的privNo串
        SysPara priv = sysParaMapper.querySysPara("BUDGET_EDIT_PRIV");

        if(user==null){
            user = new SysPara();
            user.setParaName("BUDGET_EDIT_USER");
            user.setParaValue("");
            sysParaMapper.insertSysPara(user);
        }

        if(priv==null){
            priv = new SysPara();
            priv.setParaName("BUDGET_EDIT_PRIV");
            priv.setParaValue("");
            sysParaMapper.insertSysPara(priv);
        }

        // 转化数组
        String[] userIds = user.getParaValue().split(",");
        String[] privNos = priv.getParaValue().split(",");

        // 遍历查找
        for (String u : userIds) {
            if (u.equals(userId)) {
                return true;
            }
        }
        for (String p : privNos) {
            if (p.equals(privNo)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据缓存map将userId串转化为username串
     *
     * @param cacheMap 缓存map/<userId,username>
     * @param userIds  userId串
     * @return username串
     */
    private String getUsernames(Map<String, String> cacheMap, String userIds) {
        if (StringUtils.checkNull(userIds)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        String[] arr = userIds.split(",");
        for (String userId : arr) {
            sb.append(cacheMap.get(userId)).append(",");
        }
        return sb.toString();
    }

    /**
     * 根据userId串获取缓存map
     *
     * @param allUserIds userId串
     * @return 缓存map/<userId,username>
     */
    private Map<String, String> getCacheMap(StringBuilder allUserIds) {
        // 转换成数组并去重
        String str = allUserIds.toString();
        String[] arr = str.split(",");
        Set<String> set = new HashSet<>(Arrays.asList(arr));
        arr = set.toArray(new String[0]);
        // 查询userId和username
        List<Users> userList = usersMapper.getUsersByUserIds(arr);
        // put到缓存的map中
        Map<String, String> cacheMap = new HashMap<>();
        for (Users u : userList) {
            cacheMap.put(u.getUserId(), u.getUserName());
        }
        return cacheMap;
    }

    public List<Attachment> returnAttachment1(String attachmentName, String attachmentId, String sqlType, String module) {
        List<Attachment> list = new ArrayList<Attachment>();
        if (StringUtils.checkNull(attachmentId) && StringUtils.checkNull(attachmentName)) {
            return list;
        } else {
            try {
                if (attachmentId.contains("@")) {
                    String[] attachmentIds = attachmentId.split(",");
                    String[] attachmentNames = attachmentName.split("\\*");
                    int attachmentidLength = attachmentIds.length;
                    for (int i = 0; i < attachmentidLength; i++) {
                        Integer attachId1=Integer.parseInt(attachmentIds[i].substring(attachmentIds[i].indexOf("_")+1,attachmentIds[i].length()));
                        Attachment attachment = enclosureService.findByAttachId1(attachId1);
                        if (attachment != null) {
                            if (".mp4".equals(attachment.getAttachName().substring(attachment.getAttachName().indexOf("."), attachment.getAttachName().length()))
                                    || ".rmvb".equals(attachment.getAttachName().substring(attachment.getAttachName().indexOf("."), attachment.getAttachName().length()))
                                    || ".avi".equals(attachment.getAttachName().substring(attachment.getAttachName().indexOf("."), attachment.getAttachName().length()))
                                    || ".ifo".equals(attachment.getAttachName().substring(attachment.getAttachName().indexOf("."), attachment.getAttachName().length()))
                                    || ".wmv".equals(attachment.getAttachName().substring(attachment.getAttachName().indexOf("."), attachment.getAttachName().length()))

                                    ) {
                                attachment.setAttUrl("/img/video/"+attachment.getAttachId()+"."+ attachment.getAttachName());
                            }
                            else{
                                attachment.setAttUrl("AID=" + attachment.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId() + "&ATTACHMENT_NAME=" + attachment.getAttachName());

                            }
                            StringBuffer id = new StringBuffer();
                            StringBuffer name = new StringBuffer();
                            int aid = attachment.getAid();
                            String attachId = attachment.getAttachId();
                            String ym = attachment.getYm();
                            String attachName = attachment.getAttachName();
                            String all = aid + "@" + ym + "_" + attachId;
                            id.append(all).append(",");
                            name.append(attachName).append("*");
                            attachment.setId(id.toString());
                            attachment.setName(name.toString());
                            list.add(attachment);
                        }
                    }
                } else {

                    String[] attachmentIds = attachmentId.split(",");
                    String[] attachmentNames = attachmentName.split("\\*");
                    int attachmentidLength = attachmentIds.length;
                    for (int i = 0; i < attachmentidLength; i++) {
                /*		Attachment att = new Attachment();
                        att.setAttachName(attachmentNames[i]);
						att.setAid(1024);
						att.setYm(attachmentIds[i].substring(0, attachmentIds[i].lastIndexOf("_")));
						att.setAttachId(Integer.valueOf(attachmentIds[i].substring(attachmentIds[i].indexOf("_") + 1, attachmentIds[i].length())));
						att.setAttUrl("AID=" + att.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + att.getYm() + "&ATTACHMENT_ID=" + att.getAttachId() + "&ATTACHMENT_NAME=" + att.getAttachName());
					*/

                        Attachment attachment = enclosureService.findByAttachId1(Integer.parseInt(attachmentIds[i].substring(0, attachmentIds[i].indexOf("@"))));
                        if (attachment != null) {
                            attachment.setAttUrl("AID=" + attachment.getAid() + "&MODULE=" + module + "&COMPANY=" + sqlType + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId() + "&ATTACHMENT_NAME=" + attachment.getAttachName());
                            StringBuffer id = new StringBuffer();
                            StringBuffer name = new StringBuffer();
                            int aid = attachment.getAid();
                            String attachId = attachment.getAttachId();
                            String ym = attachment.getYm();
                            String attachName = attachment.getAttachName();
                            String all = aid + "@" + ym + "_" + attachId;
                            id.append(all).append(",");
                            name.append(attachName).append("*");
                            attachment.setId(id.toString());
                            attachment.setName(name.toString());
                            list.add(attachment);
                        }


                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return list;
        }
    }


}